#
# fusion.discovery.opendht
#
# Copyright 2007-2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Toni Ruottu <toni.ruottu@iki.fi>
#          Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from __future__ import with_statement
from contextlib import contextmanager

import logging
import hashlib
import random
import socket
import xmlrpclib
from xmlrpclib import Binary

application = 'P2P-Fusion'
urls = ['http://openlookup.appspot.com/']
#urls = ['http://planetlab1.Millennium.Berkeley.EDU:5851/',
#        'http://opendht.nyuld.net:5851/']

status_messages = {0: 'successful',
                   1: 'over capacity',
                   2: 'try again'}

class Error(Exception): pass

def put(key, value, ttl, secret=None):
    proxy = get_server_proxy()
    key = hashlib.sha1(key).digest()
    with reraise_exception():
        if secret is None:
            return proxy.put(Binary(key),
                             Binary(value),
                             int(ttl),
                             application)
        else:
            shash = hashlib.sha1(secret).digest()
            return proxy.put_removable(Binary(key),
                                       Binary(value),
                                       "SHA",
                                       Binary(shash),
                                       int(ttl),
                                       application)

def rm(key, value, secret, ttl=7*24*3600):
    proxy = get_server_proxy()
    key = hashlib.sha1(key).digest()
    vhash = hashlib.sha1(value).digest()
    with reraise_exception():
        return proxy.rm(Binary(key),
                        Binary(vhash),
                        "SHA",
                        Binary(secret),
                        int(ttl),
                        application)

def get(key, maxvals=2**31-1):
    proxy = get_server_proxy()
    key = hashlib.sha1(key).digest()
    placemark = Binary('')
    with reraise_exception():
        values, placemark = proxy.get(Binary(key),
                                     int(maxvals),
                                     placemark,
                                     application)
        return [v.data for v in values]

def get_server_proxy():
    url = random.choice(urls)
    return xmlrpclib.ServerProxy(url)

def interpret_result(result, client_name='OpenDHT'):
    msg = '%s: %s' % (client_name, get_status_message(result))
    if result == 0:
        logging.debug(msg)
        return True
    else:
        logging.warn(msg)
        return False

def get_status_message(result):
    return status_messages.get(result, 'unknown result code')

@contextmanager
def reraise_exception():
    try:
        yield
    except socket.timeout:
        raise Error('Timeout connecting to OpenDHT.')
    except socket.error:
        raise Error('Failed to connect to OpenDHT.')
    except xmlrpclib.Error:
        raise Error('Got XMLRPC error from OpenDHT.')
